/*
 * 文件名：SystemTimer.java
 * 版权：Copyright by will_awoke
 * 描述：
 * 修改人：lyh
 * 修改时间：2014-5-26
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.qbgs.util;


import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;


/**
 * 出自 taobao.code
 * 性能更高的系统时间类，适用于精度不是特别高的场景，精度取决于tickUnit刷新时间
 * 另外请参考：System.currentTimeMillis and System.nanoTime
 * @author will_awoke
 * @version 2014-5-26
 * @see SystemTimer
 * @since
 */
public class SystemTimer
{

    /**
     * log
     */
    private static final Logger log = Logger.getLogger(SystemTimer.class);
    
    /**
     * executor
     */
    private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    /**
     * 刷新时间
     */
    private static final long tickUnit = 50;

    /**
     * 初始化
     */
    private static volatile long time = System.currentTimeMillis();

    /**
     * thread
     */
    private static class TimerTicker implements Runnable
    {
        @Override
        public void run()
        {
            time = System.currentTimeMillis();
        }
    }

    static
    {
        executor.scheduleAtFixedRate(new TimerTicker(), tickUnit, tickUnit, TimeUnit.MILLISECONDS);
        Runtime.getRuntime().addShutdownHook(new Thread()
        {
            @Override
            public void run()
            {
                log.info("SystemTimer shutdown hook run...");
                shutdownScheduledExecutor();
            }
        });
    }

    /**
     * public method that returns currentTimeMillis as System#currentTimeMillis()
     * @return 
     * @see
     */
    public static long currentTimeMillis()
    {
        log.debug("currentTimeMillis() return time : " + time);
        return time;
    }
    
    /**
     * shutdownScheduledExecutor
     *  
     * @see
     */
    public static void shutdownScheduledExecutor()
    {
        log.info("try to shutdown ScheduledExecutor... ");
        executor.shutdown();
    }
    
    /**
     * for test
     * @param args 
     * @see
     */
    public static void main(String[] args)
    {
        currentTimeMillis();
        System.exit(0);
    }
}

